<template>
  <div class="app-container">
    <el-form label-width="120px" size="small">
      <div
        style="
          background-color: #e0e0e0;
          width: 100%;
          padding: 0 10px;
          margin: 10px 0;
        "
      >
        <h3>基本信息</h3>
      </div>
      <el-form-item label="sku名称">
        <el-input v-model="skuInfo.skuName" />
      </el-form-item>
      <el-form-item label="商品分类" prop="categoryId">
        <category-cascader :catelogPath.sync="catelogPath"></category-cascader>
      </el-form-item>
      <el-form-item label="商品售价：">
        <el-input v-model="skuInfo.price"></el-input>
      </el-form-item>
      <el-form-item label="排序">
        <el-input v-model="skuInfo.sort"></el-input>
      </el-form-item>

      <div
        style="
          background-color: #e0e0e0;
          width: 100%;
          padding: 0 10px;
          margin: 10px 0;
        "
      >
        <h3>平台属性</h3>
      </div>
      <el-form-item label="属性分组" prop="groupId">
        <el-select
          v-model="skuInfo.attrGroupId"
          placeholder="请选择"
          @change="selectGroupChange"
        >
          <el-option
            v-for="attrGroup in attrGroupList"
            :key="attrGroup.id"
            :label="attrGroup.name"
            :value="attrGroup.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="平台属性：">
        <el-card shadow="never" class="cardBg">
          <div
            :key="item.id"
            v-for="(item, index) in attrList"
            :class="{ littleMarginTop: index !== 0 }"
          >
            <div class="paramInputLabel">{{ item.name }}:</div>
            <el-select
              class="paramInput"
              v-model="attrList[index].value"
              style="width: 300px"
            >
              <el-option
                v-for="item in getParamSelectList(item.valueSelect)"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
            <!-- <el-input
              v-else
              class="paramInput"
              v-model="attrList[index].value"
              style="width: 300px"
            ></el-input> -->
          </div>
        </el-card>
      </el-form-item>

      <div
        style="
          background-color: #e0e0e0;
          width: 100%;
          padding: 0 10px;
          margin: 10px 0;
        "
      >
        <h3>商品图片</h3>
      </div>
      <el-form-item label="图片上传">
        <single-upload v-model="skuInfo.imgUrl"></single-upload>
      </el-form-item>

      <div
        style="
          background-color: #e0e0e0;
          width: 100%;
          padding: 0 10px;
          margin: 10px 0;
        "
      >
        <h3>商品库存</h3>
      </div>
      <el-form-item label="商品库存：">
        <el-input v-model="skuInfo.stock"></el-input>
      </el-form-item>

      <!--      <div style="background-color:#E0E0E0;width: 100%;padding: 0 10px;margin: 10px 0;"><h3>商品详情</h3></div>-->
      <!--      <el-form-item label="商品详情">-->
      <!--        <el-input v-model="skuInfo.skuDetail.detailHtml" type="textarea" :rows="10"></el-input>-->
      <!--      </el-form-item>-->

      <el-form-item>
        <el-button type="primary" @click="saveOrUpdate">保存</el-button>
        <el-button @click="back">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import SkuinfoApi from "@/api/product/skuinfo";
import GroupApi from "@/api/product/group";
import AttrApi from "@/api/product/attribute";

import CategoryCascader from "../../common/category-cascader";
import SingleUpload from "@/components/upload/singleUpload";

const defaultForm = {
  id: "",
  categoryId: "",
  attrGroupId: "",
  skuType: 0,
  skuName: "",
  perLimit: 1,
  isNewPerson: 0,
  sort: "",
  imgUrl: "",
  skuCode: "",
  price: "",
  marketPrice: "",
  stock: "",
  lowStock: "",
  skuAttrValueList: [],
  skuPosterList: [],
  skuImagesList: [],
};

export default {
  components: {
    CategoryCascader,
    SingleUpload,
  },
  data() {
    return {
      skuInfo: defaultForm,
      saveBtnDisabled: false,
      attrGroupList: [],
      attrList: [],
      catelogPath: [],
    };
  },

  // 监听器
  watch: {
    $route(to, from) {
      this.init();
    },
    catelogPath(path) {
      this.skuInfo.categoryId = path[path.length - 1];
      GroupApi.getGroupList({ categoryId: this.skuInfo.categoryId }).then(
        (response) => {
          this.attrGroupList = response.data;
        }
      );
    },
  },
  created() {
    this.init();
  },

  methods: {
    // 表单初始化
    init() {
      if (this.$route.params && this.$route.params.id) {
        const id = this.$route.params.id;
        this.fetchDataById(id);
      } else {
        this.skuInfo = { ...defaultForm };
      }
    },
    fetchAttrList(attrGroupId) {
      AttrApi.getDataList({ groupId: attrGroupId }).then((response) => {
        this.attrList = response.data;

        // 修改属性回显
        if (this.skuInfo.skuAttrValueList.length > 0) {
          this.attrList.forEach((attrItem) => {
            this.skuInfo.skuAttrValueList.forEach((valueItem) => {
              if (attrItem.id === valueItem.attrId) {
                attrItem.value = valueItem.attrValue;
              }
            });
          });
        }
      });
    },

    getParamSelectList(selectList) {
      console.log(selectList);
      return selectList.split(";");
    },

    selectGroupChange(attrGroupId) {
      this.fetchAttrList(attrGroupId);
    },

    saveOrUpdate() {
      if (!this.skuInfo.id) {
        this.saveData();
      } else {
        this.updateData();
      }
    },

    // 新增
    saveData() {
      const attrListArray = [];
      this.attrList.forEach((item) => {
        attrListArray.push({
          attrId: item.id,
          attrName: item.name,
          attrValue: item.value,
        });
      });
      this.skuInfo.skuAttrValueList = attrListArray;
      //   if (this.skuInfo.skuImagesList.length > 0) {
      //     this.skuInfo.imgUrl = this.skuInfo.skuImagesList[0].imgUrl;
      //   }
      SkuinfoApi.createSkuinfo(this.skuInfo).then((response) => {
        if (response.code) {
          this.$message({
            type: "success",
            message: response.data,
          });
          this.$router.push({ path: "/product/skuinfo" });
          this.saveBtnDisabled = false;
        }
      });
    },

    // 根据id更新记录
    updateData() {
      debugger;
      const attrListArray = [];
      this.attrList.forEach((item) => {
        attrListArray.push({
          attrId: item.id,
          attrName: item.name,
          attrValue: item.value,
        });
      });
      this.skuInfo.skuAttrValueList = attrListArray;
      if (this.skuInfo.skuImagesList.length > 0) {
        this.skuInfo.imgUrl = this.skuInfo.skuImagesList[0].imgUrl;
      }
      SkuinfoApi.updateById(this.skuInfo).then((response) => {
        if (response.code) {
          this.$message({
            type: "success",
            message: response.message,
          });
          this.$router.push({ path: "/product/skuinfo" });
        }
      });
    },

    back() {
      this.$router.push({ path: "/product/skuinfo" });
    },

    // 根据id查询记录
    fetchDataById(id) {
      SkuinfoApi.getSkuInfo(id).then((response) => {
        this.skuInfo = response.data;

        // 平台属性回显
        this.fetchAttrList(this.skuInfo.attrGroupId);

        // 图片回显
        this.skuInfo.skuImagesList.forEach((item) => {
          let obj = new Object();
          obj.url = item.imgUrl;
          this.fileList.push(obj);
        });

        this.skuInfo.skuPosterList.forEach((item) => {
          let obj = new Object();
          obj.url = item.imgUrl;
          this.filePosterList.push(obj);
        });
      });
    },
  },
};
</script>
<style scoped>
.littleMarginTop {
  margin-top: 10px;
}

.paramInput {
  width: 250px;
}

.paramInputLabel {
  display: inline-block;
  width: 100px;
  text-align: right;
  padding-right: 10px;
}

.cardBg {
  background: #f8f9fc;
}
</style>
